package com.example.yyy

import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.PixelFormat
import android.os.Binder
import android.os.Build

import android.os.IBinder
import android.util.Log
import android.view.WindowManager
import android.widget.Button
import android.widget.EditText
import kotlin.math.log


class FloatingService : Service() {
    /** 标识服务如果被杀死之后的行为  */
    var mStartMode = 0

    /** 绑定的客户端接口  */
    private val mBinder: IBinder = TestBinder()

    /** 标识是否可以使用onRebind  */
    var mAllowRebind = false

    override fun onCreate() {
        super.onCreate()
    }

    /** 调用startService()启动服务时回调  */
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val bundle = intent?.extras
        val string = bundle?.getString("request_content")?: "Intent as null"
        showFloatingWindow(string,true)
        return mStartMode
    }

    override fun onBind(intent: Intent?): IBinder? {
        return mBinder
    }

    /** 通过unbindService()解除所有客户端绑定时调用  */
    override fun onUnbind(intent: Intent?): Boolean {
        return mAllowRebind
    }

    /** 通过bindService()将客户端绑定到服务时调用 */
    override fun onRebind(intent: Intent?) {}

    /** 服务不再有用且将要被销毁时调用  */
    override fun onDestroy() {
        showFloatingWindow("",false)
        super.onDestroy()
    }

    inner class TestBinder : Binder() {
        fun getService() :FloatingService {
            return this@FloatingService
        }
    }

    fun showFloatingWindow(str:String,boolean: Boolean){
        //获取WindowManager
        val windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
        //新建悬浮窗
        val button = EditText(applicationContext)
        button.setText("")
        button.setBackgroundColor(Color.BLUE);
        button.setOnClickListener {
            Log.e("TAG", "onStartCommand: "+str )
        }

        //设置layoutParams
        val layoutParams = WindowManager.LayoutParams()
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
            layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        }else{
            layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        }
        layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or  WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM
        layoutParams.format = PixelFormat.RGBA_8888;
        layoutParams.width = 500
        layoutParams.height = 100;
        layoutParams.x = 30;
        layoutParams.y = 300;

        // 将悬浮窗控件添加到WindowManager
        if (boolean)windowManager.addView(button, layoutParams)  else  windowManager.removeView(button)
    }
}
